import time
from datetime import date, timedelta

import aiohttp
import asyncio
import json
import hashlib
from datetime import datetime

import logging

from sqlalchemy.sql.functions import current_timestamp

from logging_config import setup_logger  # 导入但无需调用
logger = logging.getLogger(__name__)

eccang_config = {
    "api_url": "http://openapi-web.eccang.com/openApi/api/unity",
    "app_key": "5a88960690464f04",
    "secret_key": "87faeb0bbb14eb59",
    "version": "V1.0.0",
    "service_id": "ECR0LB",
    "sign_type": "MD5",
    "timestamp": "1646454400000",
    "charset": "UTF-8",
    "format": "json",
    "method": "POST",
    "nonce_str": "123456",
}

eccang_api_headers = {
    "Content-Type": "application/json",
    "ContentType": "application/json",
}

# 基础请求方法
async def fetch_base(interface_method, biz_content, sign, timestamp, params=None, data=None, headers=None):
    request_raw = {
        "app_key": eccang_config.get("app_key"),
        "biz_content": json.dumps(biz_content).replace(" ", ""),
        "interface_method": interface_method,
        "charset": eccang_config.get("charset"),
        "nonce_str": eccang_config.get("nonce_str"),
        "service_id": eccang_config.get("service_id"),
        "sign_type": eccang_config.get("sign_type"),
        "timestamp": timestamp,
        "version": eccang_config.get("version"),
        "sign": sign,
    }

    result_data = {}
    print(request_raw)
    async with aiohttp.ClientSession() as session:
        async with session.post(eccang_config.get("api_url"), params=None, data=json.dumps(request_raw), headers=eccang_api_headers) as response:
            if response.status == 200:
                result_data = await response.json()
                if(result_data.get("code") != '200'):
                    print(f"接口请求失败，返回结果：{result_data}")
                    return None
                if(result_data.get("biz_content") is None):
                    print(f"接口请求，返回结果空：{result_data}")
                return result_data.get("biz_content")
            else:
                print(f"接口请求失败，状态码：{response.status}")
    return result_data

# 签名生成
def generate_md5_sign(biz_content, timestamp):
    sign_org_str = "app_key={}&biz_content={}&charset=UTF-8&interface_method=getProductTrouble&nonce_str=123456&service_id=ECR0LB&sign_type=MD5&timestamp={}&version=V1.0.0{}".format(
        eccang_config.get("app_key"),
        biz_content,
        timestamp,
        eccang_config.get("secret_key")
    )
    sign_org_str = sign_org_str.replace(" ", "")
    print(sign_org_str)
    md5 = hashlib.md5()
    md5.update(sign_org_str.encode("utf-8"))
    return md5.hexdigest()

# 获取产品问题接口
async def fetch_getProductTrouble():
    timestamp = int(time.time()*1000)  # 获取当前时间戳
    pre_day = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d")  # 获取昨天日期
    cur_day = (date.today()).strftime("%Y-%m-%d")  # 获取昨天日期
    biz_content = {
        "page":1,
        "page_size":100,
        "date_for":pre_day,
        "date_to":cur_day
    }
    biz_content_json = json.dumps(biz_content)
    sign = generate_md5_sign(biz_content_json, timestamp)
    return await fetch_base("getProductTrouble", biz_content, sign, timestamp)

from feishu import feishu_api

# 保存易仓数据到飞书多维表
def save_eccang_data_to_feishu():
    print("eccang_api")
    result = asyncio.run(fetch_getProductTrouble())
    print("正常返回结果：", result)
    resust_dict = json.loads(result)
    data_list = resust_dict.get("data")
    current_timestamp = int(datetime.now().timestamp() * 1000)   # 毫秒时间戳

    for item in data_list:

        item['sync_time'] = current_timestamp
        if "po_code" in item: del item["po_code"]
        if "pte_id" in item: del item["pte_id"]
        if "ptt_id" in item: del item["ptt_id"]
        if "ptp_id" in item: del item["ptp_id"]
        if "pttg_id" in item: del item["pttg_id"]
        if "ptt_imgs" in item: del item["ptt_imgs"]
        if "ptt_create_date" in item:
            dt = datetime.strptime(item["ptt_create_date"], "%Y-%m-%d %H:%M:%S")
            item["ptt_create_date"] = int(dt.timestamp() * 1000)  # 转换为毫秒时间戳
        if "ptt_creater" in item: del item["ptt_creater"]
        if "product_id" in item: del item["product_id"]
        if "pte_name_en" in item: del item["pte_name_en"]
        if "ptp_name_en" in item: del item["ptp_name_en"]

    asyncio.run(feishu_api.eccang_product_trouble_to_feishu(data_list))

if __name__ == '__main__':
    print("save_eccang_data_to_feishu")
    save_eccang_data_to_feishu()